<template>
  <div>
    <px-button v-has="'BAG_MAU_CREATE'" class="mb-4" type="primary" @click="createOrder">创建工单</px-button>
    <div v-loading="loading" class="list-info-table">
      <px-table :data="data" size="small" border class="common-table" height="calc(100vh - 229px)" @selection-change="handleSelectionChange">
        <px-table-column type="selection" width="55" />
        <px-table-column prop="ffuCode" label="设备位号" width="220" />
        <px-table-column prop="group" label="耗材类别" min-width="180">
          <template #default="scope">
            <div
              v-for="(item, ind) in scope.row.filters"
              :key="ind"
              class="filter_bro"
              :style="{ minHeight: `${24 * Object.values(scope.row.filters)[ind].length}px` }"
            >
              {{ item.filterType }}
            </div>
          </template>
        </px-table-column>
        <px-table-column prop="status" label="过滤器状态" min-width="100">
          <template #default="scope">
            <div v-for="(item, ind) in scope.row.filters" :key="ind" class="filter_bro">
              <div :style="{ color: initStatusColor(item) }">
                {{ initStatus(item) }}
              </div>
            </div>
          </template>
        </px-table-column>
        <px-table-column prop="startTime" label="耗材安装日期" min-width="120">
          <template #default="scope">
            <div v-for="(item, ind) in scope.row.filters" :key="ind" class="filter_bro">
              <div class="text">{{ dayjs(item.filterInstallDate).format("DD/MM/YYYY") }}</div>
            </div>
          </template>
        </px-table-column>
        <px-table-column prop="lifecycle_exp" label="剩余寿命(天)" min-width="150">
          <template #default="scope">
            <div v-for="(item, ind) in scope.row.filters" :key="ind" class="filter_bro">
              <div class="flex justify-center" :style="{ color: initStatusColor(item) }">
                <div class="progress flex items-center">
                  <PxProgress
                    :style="{ flex: 1, width: 116 }"
                    :percentage="item.lifecycle_exp ? Math.round((100 * item.lifecycle_exp_left) / item.lifecycle_exp) : 0"
                    :color="initStatusColor(item)"
                  />
                </div>
                <div class="reset-day flex">
                  <div :style="{ color: initStatusColor(item) }">{{ item.lifecycle_exp_left ?? "--" }}</div>
                  /
                  <div>{{ item.lifecycle_exp ?? "--" }}</div>
                </div>
              </div>
            </div>
          </template>
        </px-table-column>
        <px-table-column prop="filterInstallDate" label="上次更换工单" min-width="120">
          <template #default="scope">
            <div v-for="(item, ind) in scope.row.filters" :key="ind" class="filter_bro">
              <div class="table-body-item-6">{{ dayjs(item.filterInstallDate).format("DD/MM/YYYY") }}</div>
            </div>
          </template>
        </px-table-column>
        <px-table-column prop="filterNextInstallDate" label="预测更换时间" min-width="120">
          <template #default="scope">
            <div v-for="(item, ind) in scope.row.filters" :key="ind" class="filter_bro">
              <div class="table-body-item-7 flex">
                <div class="date">{{ dayjs(item.filterNextInstallDate).format("DD/MM/YYYY") }}</div>
                <div class="days" :style="{ color: initStatusColor(item) }">{{ item.lifecycle_exp_left }}天</div>
              </div>
            </div>
          </template>
        </px-table-column>
        <px-table-column label="操作" min-width="100">
          <template #default="scope">
            <div class="flex justify-center justify-around">
              <!-- <div v-has="'GHVAC_JUMP_1'" class="jump1" @click="handleToPage(scope.row, 1)">
                <img class="img_op" :src="project" />
              </div>
              <div v-has="'GHVAC_JUMP_2'" class="jump2" @click="handleToPage(scope.row, 2)"><img class="img_op" :src="list" /></div>
              <div v-has="'GHVAC_JUMP_3'" class="jump3" @click="handleToPage(scope.row, 3)"><img class="img_op" :src="record" /></div> -->
              <px-tooltip class="box-item" content="更换耗材" placement="top">
                <waterSwitch v-has="'GHVAC_JUMP_1'" class="svg-icon" @click="routerToChangeHanlder(scope.row)" />
              </px-tooltip>
              <px-tooltip class="box-item" content="耗材记录" placement="top">
                <waterTime v-has="'GHVAC_JUMP_2'" class="svg-icon" @click="routerToHistoryHanlder(scope.row)" />
              </px-tooltip>
              <px-tooltip class="box-item" content="工单记录" placement="top">
                <waterStore v-has="'GHVAC_JUMP_3'" class="svg-icon" @click="routerToWorkOrderRecord(scope.row)" />
              </px-tooltip>
            </div>
          </template>
        </px-table-column>
      </px-table>
      <!-- <add v-if="isShowAddDialog" v-model="isShowAddDialog" :data="filterData" @submit="submitHandler" /> -->
      <!-- <associationAnalysis ref="associationAnalysisRef" /> -->
    </div>
  </div>
</template>
<script setup lang="ts">
defineOptions({
  name: "tableList"
});

import { ref } from "vue";
import { PxMessage, PxProgress } from "px-ui";
import dayjs from "dayjs";
import { useRouter } from "vue-router";
import { getToken } from "@/utils/auth";
import { queryTypeCode } from "@/api/modules/machine";
import waterSwitch from "@/assets/svg/water/waterSwitch.svg?component";
import waterStore from "@/assets/svg/water/waterStore.svg?component";
import waterTime from "@/assets/svg/water/waterTime.svg?component";

const router = useRouter();

const props = defineProps({
  loading: {
    type: Boolean,
    default: false
  },
  storageData: {
    type: Object,
    default: () => ({})
  }
});

const data = ref<Array<Record<string, any>>>([]);
const filterData = ref<any>([]);

// TODO: 旧代码类型已经不能满足多次迭代之后的业务了，后续要整理
const typeData = {
  MAU: {
    typeCode: "EQP_MAU",
    itemValue: "EQP_MAU"
  },
  NMAU: {
    typeCode: "EQP_NMAU",
    itemValue: "EQP_NMAU"
  },
  AHU: {
    typeCode: "EQP_AHU",
    itemValue: "EQP_AHU"
  },
  PCW: {
    typeCode: "EQP_PCW",
    itemValue: "EQP_PCW"
  }
};

const createOrder = async () => {
  if (filterData.value && filterData.value.length) {
    const devType = filterData.value.map(item => item.devType)[0];
    const params = typeData[devType];
    const res = await queryTypeCode(params, () => {});
    const { EQP_TYPE_ID, SPARE_PART_SPECIFICATION_CODE } = res?.itemDesc ? JSON.parse(res.itemDesc) : { EQP_TYPE_ID: "" };
    const accessToken = getToken().accessToken || "";
    const facCode = localStorage.getItem("facCode");
    router.push({
      path: "/all/equip/epm/plan/list",
      query: {
        fullpath: `/pmPlan/list?pmType=UNS&isAdd=true&ssoToken=${accessToken}&isHiddenMenu=true&eqpId=${EQP_TYPE_ID}&facCode=${facCode}&className=MACHINE`
      }
    });
  } else {
    PxMessage.error("请选择设备位号！！");
  }
};

const initData = (arr: any) => {
  data.value = arr;
};

// 过滤器状态
const initStatus = (items: any) => {
  let msg = "--";

  if (items.outdated && !items?.invalid) {
    msg = "临期";
  }
  if (items.invalid) {
    msg = "失效";
  }
  if (!items.invalid && !items.outdated) {
    msg = "健康";
  }
  return msg;
};
// 过滤器状态 颜色
const initStatusColor = (items: any) => {
  let color = "#000";

  if (items.outdated) {
    color = "#FFBD00";
  }
  if (items.invalid) {
    color = "#FF0000";
  }
  if (!items.invalid && !items.outdated) {
    color = "#10B981";
  }
  return color;
};

// 操作跳转
const handleToPage = async (row: any, type: any) => {
  const facCode = localStorage.getItem("facCode");
  const params = typeData[row.devType];
  const res = await queryTypeCode(params, () => {});
  const { EQP_TYPE_ID, SPARE_PART_SPECIFICATION_CODE } = res?.itemDesc
    ? JSON.parse(res.itemDesc)
    : { EQP_TYPE_ID: "", SPARE_PART_SPECIFICATION_CODE: "" };
  const accessToken = getToken().accessToken || "";
  if (type == 1) {
    // 跳转到耗材记录
    router.push({
      path: "/machine/consumableItemsLifecycle/record",
      query: {
        ffuCode: row.ffuCode,
        filterSpc: row.filterSpc,
        className: "MACHINE" //GAS:气课，MACHINE:机械科,ELECTRICTITY:电科，WATER：水科
      }
    });
  }
  if (type == 2) {
    // 跳转至突发型保养计划
    router.push({
      path: "/all/equip/epm/plan/list",
      query: {
        fullpath: `/pmPlan/list?pmType=UNS&isAdd=true&ssoToken=${accessToken}&isHiddenMenu=true&eqpId=${EQP_TYPE_ID}&ruleCode=${SPARE_PART_SPECIFICATION_CODE}&facCode=${facCode}&className=MACHINE&subType=REF_TEMPLATE`
      }
    });
  }
  if (type == 3) {
    // 跳转至pms任务列表页
    router.push({
      path: "/all/equip/epm/task/list",
      query: {
        fullpath: `/pmJob/list?pmType=${row.devType}&ssoToken=${accessToken}&isHiddenMenu=true&eqpId=${EQP_TYPE_ID}&ruleCode=${SPARE_PART_SPECIFICATION_CODE}&facCode=${facCode}&className=MACHINE`
      }
    });
  }
};
/**更换耗材 */
const routerToChangeHanlder = (row: any) => {
  console.log("row", row);
  router.push({
    path: "/all/equip/epm/plan/list",
    query: {
      fullpath: `/pmPlan/list?pmType=UNS&isAdd=true&ssoToken=${getToken().accessToken || ""}&isHiddenMenu=true&eqpId=${row.ffuId}&ruleCode=${row.ffuCode}&className=MACHINE&subType=REF_TEMPLATE&facCode=${localStorage.getItem("facCode")}`
    }
  });
};

/**跳转到耗材记录 */
const routerToHistoryHanlder = (row: any) => {
  console.log(`output->row`, row);
  // router.push({ path: "/water/waterConsumable/history", query: { eqpId: row.ffuCode, filterType: row.filterType } });
  router.push({
    path: "/machine/consumableItemsLifecycle/record",
    query: {
      ffuCode: row.ffuCode,
      // filterSpc: row.filterSpc,
      filterType: row.filterType,
      className: "MACHINE" //GAS:气课，MACHINE:机械科,ELECTRICTITY:电科，WATER：水科
    }
  });
};

/**用额定寿命计算 */
const routerToWorkOrderRecord = (row: any) => {
  console.log("row", row);
  router.push({
    path: "/all/equip/epm/task/list",
    query: {
      fullpath: `/pmJob/list?pmType=${row.ffuCode}&ssoToken=${getToken().accessToken || ""}&isHiddenMenu=true&eqpId=${row.ffuId}&ruleCode=${row.ffuCode}`
    }
  });
};
const handleSelectionChange = (val: any[]) => {
  filterData.value = val;
};
defineExpose({
  initData
});
</script>

<style lang="scss" scoped>
.search {
  display: flex;
  flex-wrap: wrap;
  margin-left: 5px;

  .item {
    display: flex;
    flex-flow: row nowrap;
    margin-right: 15px;
    margin-bottom: 16px;

    .label {
      margin-top: 6px;
      font-size: 14px;
      font-weight: 400;
      line-height: 20px;
      color: #333;
    }
  }
}

.filter_bro ~ .filter_bro {
  border-top: 1px solid #e6e6e6;
}

.progress {
  width: 120px;
  height: 24px;
  border-right: 1px solid #dfdfdf;
}

.reset-day {
  display: flex;
  flex-flow: row nowrap;
  justify-content: center;
  width: 50px;
  text-align: center;
}

.text {
  width: 100%;
}

.spec {
  width: 130px;
  text-align: center;
  border-right: 1px solid #dfdfdf;
}

.num {
  width: 50px;
  text-align: center;
}

.date {
  width: 100px;
  text-align: center;
  border-right: 1px solid #dfdfdf;
}

.days {
  display: flex;
  flex-flow: row nowrap;
  justify-content: center;
  width: 50px;
  text-align: center;
}

.img_op {
  width: 16px;
  cursor: pointer;
}

.svg-icon {
  cursor: pointer;

  &:focus {
    outline: none;
  }
}
</style>
